<!--
*  2021-03-15
*  纱线合纱出库列表
-->
<template>
  <div id="app" class="outbound-list">
    <!-- 头部导航 -->
    <van-nav-bar
      ref="header"
      left-arrow
      @click-left="onClickLeft"
      left-text="返回"
    >
      <template #title>
        <span @click="onClickPrev">前一天</span>
        <span @click="show = true" style="margin: 0 10px;">{{ dateTime }}</span>
        <span @click="onClickNext">后一天</span>
      </template>
      <template #right>
        <span @click="onClickRight"><van-icon name="plus" size="20" /></span>
        <!-- <span @click="onClickNext">后一天</span> -->
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="designName" placeholder="请输入搜索关键词" />
    <!-- 总计 -->
    <van-cell
      class="outbound-list__total"
      v-show="tableData.length !== 0"
      :title="'总包数: ' + totalNum"
    >
      <template slot="default">
        <div>
          <span>{{ "筒只数: " + totalSpindleNum }}</span>
          <span>{{ "总重量: " + totalWeight }}</span>
        </div>
      </template>
    </van-cell>
    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
      :pulldown="true"
      @pulldown="onGetYarnStoreOutList"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <div v-for="(data, index) in tableData" :key="index">
          <van-cell
            :title="data.standardNo"
            :label="data.colorName + data.standard"
            class="start-cell"
          >
            <template slot="default">
              <div>
                <span class="active">{{
                  "筒只数: " + data.totalSpindleNum
                }}</span>
                <span class="active">{{ "包数: " + data.packages }}</span>
                <span class="active">{{ "重量: " + data.totalWeight }}</span>
              </div>
            </template>
          </van-cell>
          <van-cell
            v-for="(d, key) in data.details"
            :key="index + '_' + key"
            :title="'批次：' + d.lotNum"
            :class="{ end: key === data.details.length - 1 }"
          >
            <template slot="default">
              <div>
                <span>{{ "筒只数: " + d.spindleNum }}</span>
                <span>{{ "包数: " + d.packages }}</span>
                <span>{{ "重量: " + getFloat(d.weight, 1) }}</span>
              </div>
            </template>
          </van-cell>
        </div>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <!-- 日期筛选 -->
    <van-calendar
      v-model="show"
      :min-date="minDate"
      :max-date="maxDate"
      :round="false"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import { openWin, comeBack, getFloat } from "@/utils/index";
import {
  loadYarnStoreOutData,
  // getYarnPackageFilter,
  getYarnStoreOutMerge
} from "@/api/yarn";
import dayjs from "dayjs";

export default {
  name: "weavingOutboundYarn",
  data() {
    return {
      title: "",
      currentPage: 1,
      totalPage: 1,
      tableData: [
        {
          standardNo: 111,
          lotNum: 11,
          details: [
            {
              standardNo: "111",
              weight: 1111,
              lotNum: 111,
              spindleNum: 111,
              packages: 11,
            },
          ],
          packages: 11,
          totalWeight: 11,
          colorName: 11,
          totalSpindleNum: 111,
          standard: 11,
        },
      ],
      pageNum: 1,
      pageSize: 1000,
      show: false,
      designName: "",
      dateTime: dayjs().format("YYYY-MM-DD"),
      minDate: new Date(dayjs().subtract(1, "year")),
      maxDate: new Date(),
      beginAt: dayjs().format("YYYY-MM-DD 00:00:00"),
      endAt: dayjs().format("YYYY-MM-DD 24:00:00"),
      totalWeight: 0,
      totalNum: 0,
      totalSpindleNum: 0,
    };
  },
  watch: {
    // 监听出库列表
    tableData: {
      handler(val) {
        this.totalWeight = getFloat(this.countTotal(val, "totalWeight"), 1);
        this.totalSpindleNum = getFloat(
          this.countTotal(val, "totalSpindleNum"),
          0
        );
      },
      deep: true,
    },
    // 监听事件筛选
    dateTime() {
      this.onGetYarnStoreOutList();
    },
    // 监听designName
    designName(newVal, oldVal) {
      // 防止input连续输入时，频繁发请求
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // 异步请求
        if (oldVal !== newVal) {
          this.onGetYarnStoreOutList();
        }
      }, 1000);
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    getFloat,

    //初始化
    initFn(that) {
      that.onGetYarnStoreOutList();
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },

    // 返回
    onClickLeft() {
      comeBack();
    },
    // 前一天
    onClickPrev() {
      this.dateTime = dayjs(this.dateTime)
        .subtract(1, "day")
        .format("YYYY-MM-DD");
    },
    // 后一天
    onClickNext() {
      if (this.dateTime === dayjs().format("YYYY-MM-DD")) {
        this.$toast.fail("明天还没到");
        return false;
      }
      this.dateTime = dayjs(this.dateTime).add(1, "day").format("YYYY-MM-DD");
    },
    // 时间筛选
    onConfirm(val) {
      this.dateTime = dayjs(val).format("YYYY-MM-DD");
      this.show = false;
    },
    // 扫码
    onClickRight() {
      openWin("list-operate", {
        isMerge: true
      });
    },
    // 出库列表 // 下拉刷新
    onGetYarnStoreOutList(flag) {
      this.tableData = [];
      this.totalNum = 0;
      this.totalWeight = 0;
      loadYarnStoreOutData(
        {
          beginAt: dayjs(this.dateTime).format("YYYY-MM-DD 00:00:00"),
          endAt: dayjs(this.dateTime)
            .add(1, "day")
            .format("YYYY-MM-DD 00:00:00"),
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          standard: this.designName,
          refType: 96
        },
        (res) => {
          // alert(JSON.stringify(res.list));
          this.totalNum = res.list.length;
          this.tableData = this.handlerDatas(res.list);
          if (flag == "add") {
            this.$toast({
              type: "loading",
              message: "请等待",
              duration: 1000,
              onClose: () => {
                this.onClickRight();
              },
            });
          }
        }
      );
    },
    // 合纱出库
    onGetYarnStoreOutAdd(packageId) {
      getYarnStoreOutMerge(
        {
          packageIds: [packageId],
        },
        () => {
          this.$toast({
            type: "success",
            message: "出库成功",
            duration: 1000,
            onClose: () => {
              this.onGetYarnStoreOutList("add");
            },
          });
        }
      );
    },
    handlerDatas(arr) {
      let tempArr = [];
      let afterData = [];
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        item.packages = 1;
        let key = item.standardNo;

        if (tempArr.indexOf(key) === -1) {
          afterData.push({
            standardNo: key,
            lotNum: item.lotNum,
            details: [item],
            packages: item.packages,
            totalWeight: item.weight,
            colorName: item.colorName,
            totalSpindleNum: item.spindleNum,
            standard: item.standard,
          });

          tempArr.push(key);
        } else {
          for (let j = 0; j < afterData.length; j++) {
            if (afterData[j].standardNo == arr[i].standardNo) {
              let totalWeight = getFloat(
                Number(afterData[j].totalWeight) + Number(arr[i].weight),
                1
              );
              let totalSpindleNum = getFloat(
                Number(afterData[j].totalSpindleNum) +
                  Number(arr[i].spindleNum),
                0
              );
              afterData[j].totalWeight = totalWeight;
              afterData[j].totalSpindleNum = totalSpindleNum;
              afterData[j].packages++;
              for (let m = 0; m < afterData[j].details.length; m++) {
                if (afterData[j].details[m].lotNum === arr[i].lotNum) {
                  // afterData[j].details[m].weight += arr[i].weight;
                  afterData[j].details[m].weight = getFloat(
                    afterData[j].details[m].weight + arr[i].weight,
                    1
                  );
                  // afterData[j].details[m].spindleNum += arr[i].spindleNum;
                  afterData[j].details[m].spindleNum = getFloat(
                    afterData[j].details[m].spindleNum + arr[i].spindleNum,
                    0
                  );
                  afterData[j].details[m].packages++;
                } else {
                  afterData[j].details.push(arr[i]);
                }
                break;
              }
              break;
            }
          }
        }
      }
      return afterData; // 最终输出
    },
    // 计算总重量/总长度
    countTotal(arr, keyName) {
      let $total = 0;
      $total = arr.reduce(function (total, currentValue) {
        console.log(currentValue[keyName]);
        return currentValue[keyName]
          ? total + Number(currentValue[keyName])
          : Number(total);
      }, 0);
      return $total;
    },
  },
};
</script>

<style lang="scss">
.outbound-list {
  .van-search {
    position: relative;
    z-index: 999;
  }
  .van-nav-bar__title {
    display: flex;
    height: 100%;
    align-items: center;
    span {
      display: flex;
      height: 100%;
      align-items: center;
      justify-content: center;
      flex: 1;
      font-size: 14px;
      &:first-child {
        color: #1989fa;
      }
      &:last-child {
        color: #ee0a24;
      }
    }
  }
  .van-nav-bar__right {
    span {
      display: flex;
      height: 100%;
      align-items: center;
    }
  }
  .outbound-list__total {
    position: relative;
    z-index: 999;
    .van-cell__title {
      flex: 0 0 40%;
    }
    .van-cell__value {
      & > div {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }
    span {
      color: #1989fa;
      font-size: 16px;
    }
  }
  .public-scroll {
    height: calc(100vh - 174px);
    overflow: hidden;

    .van-cell {
      &:not(:nth-child(1)) {
        padding-top: 0;

        &:last-child {
          border-bottom: 1px solid #ddd !important;
        }

        .van-cell__value {
          flex: 0 0 70%;
          div {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-end;
            span {
              display: flex;
              flex: 1;
              justify-content: center;
              &:last-child {
                justify-content: flex-end;
              }
            }
          }
        }
      }
      &.start-cell {
        &.van-cell:not(:last-child)::after {
          border-bottom: none;
        }
        .van-cell__title {
          font-weight: 600;
          color: #e4393c;
        }
        .van-cell__label {
          font-weight: 600;
          color: #e4393c;
        }
        .van-cell__value {
          flex: 0 0 45%;
          div {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-end;
            span {
              display: flex;
              flex: 0 0 50%;
              justify-content: flex-end;
              &.active {
                color: #e4393c;
              }
            }
          }
        }
      }
    }
  }
}
</style>

